package com.youxin.other.report.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youxin.admin.user.client.dto.UserReportItem;
import com.youxin.base.TPage;
import com.youxin.other.report.entity.req.UserReportSearch;
import com.youxin.other.report.entity.vo.UserReportVo;
import com.youxin.other.report.mapper.UserReportMapper;
import com.youxin.other.report.model.UserReport;
import com.youxin.other.report.service.UserReportService;
import com.youxin.other.report.service.rpc.RpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;

/**
 * description: UserReportServiceImpl <br>
 * date: 2020/3/6 12:14 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class UserReportServiceImpl extends ServiceImpl<UserReportMapper, UserReport> implements UserReportService {


    private static Logger logger = LoggerFactory.getLogger(UserReportServiceImpl.class);

    private ExecutorService executor = Executors.newSingleThreadExecutor();

    @Resource
    private RpcService rpcService;

    @Override
    public void generateReport() {
        DateTimeFormatter totalFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDate yestoday = LocalDate.now().minusDays(1);
        String startTime = yestoday.atStartOfDay().format(totalFormat);
        String endTime = yestoday.atTime(LocalTime.MAX).format(totalFormat);
        UserReportSearch search = new UserReportSearch();
        search.setStartTime(startTime);
        search.setEndTime(endTime);
        List<UserReportItem> activeList = rpcService.staticActiveReport(search);
        search.setStartTime(null);
        int totalNum = rpcService.staticUserReport(search);
        search.setStartTime(startTime);
        search.setGroupDate(Boolean.TRUE);
        int addNum = rpcService.staticUserReport(search);
        remove(new LambdaQueryWrapper<UserReport>().
                ge(UserReport::getStaticTime, startTime)
                .le(UserReport::getStaticTime, endTime));
        UserReport report = new UserReport();
        report.setStaticTime(Date.from(yestoday.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
        if (!CollectionUtils.isEmpty(activeList)) {
            report.setActiveNum(activeList.get(0).getNum());
        } else {
            report.setActiveNum(0);
        }

        report.setAddNum(addNum);

        report.setTotalNum(totalNum);

        report.setCreateTime(new Date());
        save(report);
    }

    @Override
    public void generateReport(String startTime, String endTime) {
        LambdaQueryWrapper<UserReport> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ge(UserReport::getStaticTime, startTime);
        queryWrapper.le(UserReport::getStaticTime, endTime);
        this.baseMapper.delete(queryWrapper);
        LocalDate startDate = LocalDate.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate endDate = LocalDate.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate day = startDate;
        while (day.compareTo(endDate) <= 0) {
            UserReportSearch search = new UserReportSearch();
            search.setStartTime(day.atStartOfDay().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            search.setEndTime(day.atTime(LocalTime.MAX).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            List<UserReportItem> activeList = rpcService.staticActiveReport(search);
            int addNum = rpcService.staticUserReport(search);
            search.setStartTime(null);
            int totalNum = rpcService.staticUserReport(search);
            search.setStartTime(startTime);
            search.setGroupDate(Boolean.TRUE);
            UserReport report = new UserReport();
            report.setStaticTime(Date.from(day.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
            if (!CollectionUtils.isEmpty(activeList)) {
                report.setActiveNum(activeList.get(0).getNum());
            } else {
                report.setActiveNum(0);
            }
            report.setAddNum(addNum);

            report.setTotalNum(totalNum);

            report.setCreateTime(new Date());
            save(report);
            day = day.plusDays(1);
        }
    }

    @Override
    public TPage<UserReportVo> pageReport(UserReportSearch search) {
        IPage<UserReportVo> page = this.baseMapper.selectByParam(new Page<UserReportVo>(search.getCurrentPage(), search.getShowCount()), search);

        return TPage.page(page.getRecords(), page.getTotal());
    }

    @Override
    public List<UserReportVo> listReport(UserReportSearch search) {
        return this.baseMapper.selectList(search);
    }
}
